<template>
  <c-form
    style="height: 80vh; overflow: auto"
    ref="formRef"
    label-width="140px"
    width="100%"
    isDialog
    :loading="loading"
    :model="formData"
    :rows="formRows"
    @submit="onSubmit"
    @reset="onReset"
  >
  </c-form>
</template>

<script setup name="manage-center.mini-config">
import { ref, computed, onMounted } from 'vue';
import { useForm } from '@/hooks/useForm';
import { createShareCard, editeShareCard } from '@/apis/share-card.js';
import { ElMessage } from 'element-plus';
import { uploadFile, allTypeGroup } from '@/apis/user';
import { listGroup } from '@/apis/images';

import { useFetch } from '@/hooks/useFetch/index.js';

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

const emit = defineEmits(['refresh']);

const formRef = ref(null);

// 分类列表
const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: allTypeGroup,
});

// 分组列表
const groupParams = ref({ group_type: '' });
const data = modalStore.getModal('add-share-card-popup');
groupParams.value.group_type = data.image_type;
const {
  loading: groupLoading,
  data: groupData,
  queryData: queryListGroup,
} = useFetch({
  api: listGroup,
  params: groupParams.value,
});

const { loading, formData, submitForm } = useForm({
  initParams: {
    share_imgs: [],
    share_title: '',
    share_path: '',
    status: 0,
    image_type: '',
    image_group_id: '',
  },
});

const formRows = ref([
  {
    formType: 'upload-imgs',
    prop: 'share_imgs',
    size: 2,
    label: '分享卡图片：',
    required: false,
  },
  { formType: 'input', prop: 'share_title', label: '分享卡标题：' },
  { formType: 'input', prop: 'share_path', label: '分享卡跳转路径：' },
  {
    formType: 'select',
    prop: 'image_type',
    label: '关联图像类型:',
    optionList: computed(() => typeGroupData.value),
    optionProps: { label: 'label', value: 'value' },
    loading: computed(() => typeLoading.value),
    onChange: (e) => {
      groupParams.value.group_type = e;
      formData.value.image_group_id = '';
      queryListGroup();
    },
  },
  {
    formType: 'select',
    prop: 'image_group_id',
    label: '关联图像分组:',
    optionList: computed(() => groupData.value.data),
    optionProps: { label: 'name', value: '_id' },
    loading: computed(() => groupLoading.value),
  },
  {
    formType: 'switch',
    prop: 'status',
    activeValue: 0,
    inactiveValue: 1,
    label: '分享卡状态：',
  },
]);

const onSubmit = async (values, instance) => {
  console.log(formData.value, 'formData');

  instance.loading = true;

  let productImgs = [];
  for (const item of formData.value.share_imgs) {
    if (!item.uploadUrl) {
      const uploadRes = await uploadFile({
        imageBase64: item.url,
        fileName: item.file.name,
      });
      if (uploadRes.code == 0) {
        productImgs.push(uploadRes.data.fileID);
        item.uploadUrl = uploadRes.data.fileID;
      }
    } else {
      productImgs.push(item.uploadUrl);
    }
  }

  if (formData.value._id) {
    const res = await editeShareCard({
      ...formData.value,
      share_imgs: productImgs,
    });

    if (res.code == 0) {
      ElMessage.success('修改成功');
      modalStore.closeModal();
      emit('refresh');
    }
  } else {
    const res = await createShareCard({
      ...formData.value,
      share_imgs: productImgs,
    });

    if (res.code == 0) {
      ElMessage.success('添加成功');
      modalStore.closeModal();
      emit('refresh');
    }
  }

  instance.loading = false;
};

const onReset = () => {};

const initData = () => {
  const data = modalStore.getModal('add-share-card-popup');

  console.log(data, 'data');

  if (data._id) {
    const share_imgs = data.share_imgs.map((v) => {
      return { imageUrl: v, uploadUrl: v, status: 0, loading: false };
    });
    formData.value = { ...data, share_imgs: JSON.parse(JSON.stringify(share_imgs)) };
  }
};

onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped></style>
